package com.imooc.articles_mongodb_project.service.impl;

import com.imooc.articles_mongodb_project.common.Result;
import com.imooc.articles_mongodb_project.dao.LikesRepository;
import com.imooc.articles_mongodb_project.dto.LikesDTO;
import com.imooc.articles_mongodb_project.entity.Likes;
import com.imooc.articles_mongodb_project.service.ILikesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class LikeServiceImpl implements ILikesService {
    @Autowired
    private LikesRepository likesRepository;

    @Override
    public List<Likes> getAll() {
        return likesRepository.findAll();
    }

    @Override
    public Result save(LikesDTO likesDTO) {

        Optional<Likes> optionalLikes = likesRepository.findById(likesDTO.getArticleId());
        if (optionalLikes.isPresent()) {
            Likes likesOld = optionalLikes.get();
            String[] likeUsers = likesOld.getLikeUser();
            ArrayList<String> listUser = new ArrayList<>(Arrays.asList(likeUsers));

            boolean isHaveFlag = false;
            Iterator<String> iterator = listUser.iterator();

            while (iterator.hasNext()) {
                String userId = iterator.next();
                if (userId.equals(likesDTO.getUserId())) {
                    // 删除点赞用户
                    iterator.remove();
                    isHaveFlag = true;
                    break;
                }
            }
            if (!isHaveFlag) {
                listUser.add(likesDTO.getUserId());
            }

            likesOld.setLikeUser(listUser.toArray(new String[listUser.size()]));
            likesRepository.save(likesOld);
        } else {
            // 直接保存点赞数据
            Likes likes = new Likes();
            likes.setId(likesDTO.getArticleId());
            String[] userIds = {likesDTO.getUserId()};
            likes.setLikeUser(userIds);
            //保存
            likesRepository.insert(likes);
        }

        return new Result(200, "点赞完成", likesDTO.getUserId());
    }


    public Result getLikeNums(String articleId) {
        Optional<Likes> likes = likesRepository.findById(articleId);
        return likes.map(value -> new Result(200, "获取点赞数成功", value.getLikeUser().length)).orElseGet(() -> new Result(200, "获取点赞数成功", 0));
    }


}
